package bingosoft.metro.demo.service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import bingosoft.components.base.helper.ObjectHelper;
import bingosoft.components.base.model.ActionModel;
import bingosoft.components.base.service.ActionService;
import bingosoft.components.base.service.PageQueryRequest;
import bingosoft.components.base.service.Result;
import bingosoft.components.base.service.ResultEntity;
import bingosoft.components.base.service.ResultPage;
import bingosoft.metro.demo.form.DemoDepartmentForm;
import bingosoft.metro.demo.form.DemoUserForm;
import bingosoft.metro.demo.iservice.IDemoDepartmentService;
import bingosoft.metro.demo.model.DemoDepartmentModel;
import bingosoft.metro.demo.model.DemoUserModel;
import bingosoft.metro.variable.VariableFactory;
import leap.core.exception.RecordNotDeletedException;
import leap.core.exception.RecordNotFoundException;
import leap.core.exception.RecordNotSavedException;
import leap.lang.Strings;
import leap.orm.dao.Dao;
import leap.orm.query.PageResult;
import leap.orm.query.Query;

/**
 * @author feily
 * @功能描述 组织业务服务接口实现类
 * @创建时间 2018-03-02 02:23:52
 */
public class DemoDepartmentService extends ActionService implements IDemoDepartmentService {

	public static final String MESSAGE_PARAM_OBJ_NULL = "参数【demoDepartmentModel】不能为null！";
	public static final String MESSAGE_PARAM_ID_NULL = "参数【departmentId】不能为空！";
	public static final String MESSAGE_QUERY_FAIL = "查询失败！";
	public static final String MESSAGE_CREATE_SUCCESS = "创建成功！";
	public static final String MESSAGE_CREATE_FAIL = "创建失败（没有数据被创建）！";
	public static final String MESSAGE_UPDATE_SUCCESS = "修改成功！";
	public static final String MESSAGE_UPDATE_FAIL = "修改失败（ID不存在或没有数据被修改）！";
	public static final String MESSAGE_GET_SUCCESS = "获取成功！";
	public static final String MESSAGE_GET_FAIL = "获取失败（ID不存在）！";
	public static final String MESSAGE_DELETE_SUCCESS = "删除成功！";
	public static final String MESSAGE_DELETE_FAIL = "删除失败（没有数据被删除）！";
	
	/**
	 * 构建函数
	 */
	public DemoDepartmentService(){
		this.setLogClass(this.getClass());
	}
	
	@Override
	public ResultEntity<List<DemoDepartmentForm>> queryDemoDepartments(PageQueryRequest pageQueryRequest, Map<String, Object> params) {
		this.logMethodCalled("queryDemoDepartments");
		this.logParamValue("pageQueryRequest", pageQueryRequest);
		this.logParamValue("params", params);
		
		if(pageQueryRequest == null){
			pageQueryRequest = new PageQueryRequest();
		}
		
		// 根据sqlKey构建查询SQL
		String selectSql = this.buildSelectSql("");
		String sql = this.buildQuerySql(selectSql, pageQueryRequest, params);

		// 构建查询对象
		Query<DemoDepartmentModel> query = DemoDepartmentModel.<DemoDepartmentModel>query(sql).params(params);
		if(!Strings.isEmpty(pageQueryRequest.getSort())){
			query = query.orderBy(pageQueryRequest.getSort());
		}

		// 返回查询结果
		ResultEntity<List<DemoDepartmentForm>> resultEntity = new ResultEntity<List<DemoDepartmentForm>>();
		try {
			List<DemoDepartmentModel> demoDepartmentModels = query.list();
			// 构建表单类
			List<DemoDepartmentForm> demoDepartmentForms = this.buildDemoDepartmentForms(demoDepartmentModels);
			
			resultEntity.setBusinessObject(demoDepartmentForms);
		} catch (Exception ex) {
			this.logError(MESSAGE_QUERY_FAIL, ex);
			resultEntity.setSuccess(false);
			resultEntity.setMessage(Strings.format("{0}[{1}]", MESSAGE_QUERY_FAIL,ex.getMessage()));
		}
		return resultEntity;
	}

	@Override
	public ResultEntity<ResultPage<List<DemoDepartmentForm>>> pageQueryDemoDepartments(PageQueryRequest pageQueryRequest, Map<String, Object> params) {
		this.logMethodCalled("pageQueryDemoDepartments");
		this.logParamValue("pageQueryRequest", pageQueryRequest);
		this.logParamValue("params", params);

		if(pageQueryRequest == null){
			pageQueryRequest = new PageQueryRequest();
		}
		
		int pageIndex = pageQueryRequest.getIndex();
		int pageSize = pageQueryRequest.getSize();
		this.logParamValue("pageIndex", pageIndex);
		this.logParamValue("pageSize", pageSize);
		
		// 构建查询SQL
		String selectSql = this.buildSelectSql();
		pageQueryRequest.mergeFilters(selectSql, params);

		// 构建查询对象
		Query<DemoDepartmentModel> query = DemoDepartmentModel.<DemoDepartmentModel>query(pageQueryRequest.getMergeSql()).params(pageQueryRequest.getParameter());
		if(!Strings.isEmpty(pageQueryRequest.getSort())){
			query = query.orderBy(pageQueryRequest.getSort());
		}
		
		// 返回查询结果
		ResultEntity<ResultPage<List<DemoDepartmentForm>>> resultEntity = new ResultEntity<ResultPage<List<DemoDepartmentForm>>>();
		try {
			PageResult<DemoDepartmentModel> pageResult = query.pageResult(pageIndex, pageSize);
			List<DemoDepartmentModel> demoDepartmentModels = pageResult.list();
			
			// 构建表单类
			List<DemoDepartmentForm> demoDepartmentForms = this.buildDemoDepartmentForms(demoDepartmentModels);
			
			ResultPage<List<DemoDepartmentForm>> resultPage = new ResultPage<List<DemoDepartmentForm>>();
			resultPage.setRows(demoDepartmentForms);
			resultPage.setPage(pageIndex);
			resultPage.setSize(pageSize);
			resultPage.setRecords(pageResult.getTotalCount());
			resultEntity.setBusinessObject(resultPage);
			
		} catch (Exception ex) {
			this.logError(MESSAGE_QUERY_FAIL, ex);
			resultEntity.setSuccess(false);
			resultEntity.setMessage(Strings.format("{0}[{1}]", MESSAGE_QUERY_FAIL,ex.getMessage()));
		}
		return resultEntity;
	}

	@Override
	public Result createDemoDepartment(DemoDepartmentForm demoDepartmentForm) {
		this.logMethodCalled("createDemoDepartment");
		this.logParamValue("demoDepartmentForm", demoDepartmentForm);
		
		Result result = new Result();	
		
		// 参数验证
		if(demoDepartmentForm == null){
			result.setSuccess(false);
			result.setMessage(MESSAGE_PARAM_OBJ_NULL);
			return result;
		}
		
		// 构建模型类
		if(Strings.isEmpty(demoDepartmentForm.getDepartmentId())){
			demoDepartmentForm.setDepartmentId(ObjectHelper.getUUID());
		}
		
		// 构建组织
		DemoDepartmentModel demoDepartmentModel = new DemoDepartmentModel();
		demoDepartmentForm.copyTo(demoDepartmentModel);
		demoDepartmentModel.setCreateTime(new Date());
		demoDepartmentModel.setCreateUserId(VariableFactory.getUserId());
		
		// 构建用户列表
		List<ActionModel> demoUserModels = this.buildDemoUserModels(demoDepartmentForm);
		
		try {
			
			// 开启事务
	        Dao.get().doTransaction((s) -> {
	        	
	        	// 创建组织
	        	demoDepartmentModel.create();
	        	
	        	// 创建用户
	        	this.persistenceActionModels(demoUserModels);
	        });
			
			result.setMessage(MESSAGE_CREATE_SUCCESS);
		} catch (RecordNotSavedException e) {
			result.setSuccess(false);
			result.setMessage(MESSAGE_CREATE_FAIL);
		}
		return result;
	}

	@Override
	public Result updateDemoDepartment(DemoDepartmentForm demoDepartmentForm) {
		this.logMethodCalled("updateDemoDepartment");
		this.logParamValue("demoDepartmentForm", demoDepartmentForm);
		
		boolean isSuccess = true;
		Result result = new Result();	
		
		// 参数验证
		if(demoDepartmentForm == null){
			result.setSuccess(false);
			result.setMessage(MESSAGE_PARAM_OBJ_NULL);
			return result;
		}
		
		// 获取用户
		String departmentId = demoDepartmentForm.getDepartmentId();
		ResultEntity<DemoDepartmentModel> resultEntity = this.getDemoDepartmentModel(departmentId);
		if(!resultEntity.isSuccess()){
			result.setSuccess(false);
			result.setMessage(resultEntity.getMessage());
			result.setStatusCode(resultEntity.getStatusCode());
			return result;
		}
		
		// 设置值
		DemoDepartmentModel demoDepartmentModel = resultEntity.getBusinessObject();
		demoDepartmentForm.copyTo(demoDepartmentModel);
		demoDepartmentModel.setUpdateTime(new Date());
		demoDepartmentModel.setUpdateUserId(VariableFactory.getUserId());
		
		// 构建用户列表
		List<ActionModel> demoUserModels = this.buildDemoUserModels(demoDepartmentForm);
		
		try {
			// 开启事务
	        Dao.get().doTransaction((s) -> {
	        	
	        	// 修改组织
	        	demoDepartmentModel.update();
	        	
	        	// 持久化用户
	        	this.persistenceActionModels(demoUserModels);
	        });
	        
			result.setMessage(MESSAGE_UPDATE_SUCCESS);
		} catch (IllegalStateException e1) {
			isSuccess = false;
		} catch (RecordNotSavedException e2) {
			isSuccess = false;
		}

		if(!isSuccess){
			result.setSuccess(false);
			result.setMessage(MESSAGE_UPDATE_FAIL);
		}
		return result;
	}

	@Override
	public ResultEntity<DemoDepartmentForm> getDemoDepartment(String departmentId) {
		this.logMethodCalled("getDemoDepartment");
		this.logParamValue("departmentId", departmentId);
		
		ResultEntity<DemoDepartmentModel> resultEntity = this.getDemoDepartmentModel(departmentId);
		
		ResultEntity<DemoDepartmentForm> resultForm = new ResultEntity<DemoDepartmentForm>();
		resultForm.setMessage(resultEntity.getMessage());
		resultForm.setStatusCode(resultEntity.getStatusCode());
		
		if(resultEntity.isSuccess()){
			// 构建组织表单
			DemoDepartmentForm demoDepartmentForm = new DemoDepartmentForm();
			demoDepartmentForm.copyFrom(resultEntity.getBusinessObject());
			
			// 构建用户表单
			List<DemoUserForm> demoUserForms = this.buildDemoUserForms(demoDepartmentForm);
			demoDepartmentForm.setDemoUserForms(demoUserForms);
			
			resultForm.setBusinessObject(demoDepartmentForm);
		}else{
			resultForm.setSuccess(false);
		}
		return resultForm;
	}
	
	@Override
	public ResultEntity<DemoDepartmentModel> getDemoDepartmentModel(String departmentId) {
		this.logMethodCalled("getDemoDepartment");
		this.logParamValue("departmentId", departmentId);
		
		ResultEntity<DemoDepartmentModel> resultEntity = new ResultEntity<DemoDepartmentModel>();
		
		// 参数验证
		if(Strings.isEmpty(departmentId)){
			resultEntity.setSuccess(false);
			resultEntity.setMessage(MESSAGE_PARAM_ID_NULL);
			return resultEntity;
		}
		
		try {
			DemoDepartmentModel demoDepartmentModel = DemoDepartmentModel.find(departmentId);
			resultEntity.setMessage(MESSAGE_GET_SUCCESS);
			resultEntity.setBusinessObject(demoDepartmentModel);
		} catch (RecordNotFoundException e) {
			resultEntity.setSuccess(false);
			resultEntity.setMessage(MESSAGE_GET_FAIL);
		}
		return resultEntity;
	}

	@Override
	public Result deleteDemoDepartment(String departmentId) {
		this.logMethodCalled("deleteDemoDepartment");
		this.logParamValue("departmentId", departmentId);
			
		Result result = new Result();	
		
		// 参数验证
		if(Strings.isEmpty(departmentId)){
			result.setSuccess(false);
			result.setMessage(MESSAGE_PARAM_ID_NULL);
			return result;
		}
		
		try {
			// 删除用户
			DemoUserModel.deleteBy("departmentId", departmentId);
			
			// 删除组织
			DemoDepartmentModel.delete(departmentId);
			
			result.setMessage(MESSAGE_DELETE_SUCCESS);
		} catch (RecordNotDeletedException e) {
			result.setSuccess(false);
			result.setMessage(MESSAGE_DELETE_FAIL);
		}
		return result;
	}

	@Override
	protected String getTableName() {
		return DemoDepartmentModel.metamodel().getTableName();
	}

	/**
	 * 构建表单类
	 * @param demoDepartmentModels
	 * @return
	 */
	protected List<DemoDepartmentForm> buildDemoDepartmentForms(List<DemoDepartmentModel> demoDepartmentModels) {
		List<DemoDepartmentForm> demoDepartmentForms = new ArrayList<DemoDepartmentForm>();
		for (DemoDepartmentModel demoDepartmentModel : demoDepartmentModels) {
			DemoDepartmentForm demoDepartmentForm = new DemoDepartmentForm();
			demoDepartmentForm.copyFrom(demoDepartmentModel);
			demoDepartmentForms.add(demoDepartmentForm);
		}
		return demoDepartmentForms;
	}
	
	/**
	 * 构建用户表单列表
	 * @param demoDepartmentForm
	 * @return
	 */
	protected List<DemoUserForm> buildDemoUserForms(DemoDepartmentForm demoDepartmentForm) {
		List<DemoUserModel> demoUserModels = DemoUserModel.<DemoUserModel>where("departmentId = ?", demoDepartmentForm.getDepartmentId() ).list();

		List<DemoUserForm> demoUserForms = new ArrayList<DemoUserForm>();
		for (DemoUserModel demoUserModel : demoUserModels) {
			DemoUserForm demoUserForm = new DemoUserForm();
			demoUserForm.copyFrom(demoUserModel);
			demoUserForms.add(demoUserForm);
		}
		return demoUserForms;
	}

	/**
	 * 构建用户模型列表
	 * @param demoDepartmentForm
	 * @return
	 */
	protected List<ActionModel> buildDemoUserModels(DemoDepartmentForm demoDepartmentForm) {
		List<ActionModel> demoUserModels = new ArrayList<ActionModel>();
		for (DemoUserForm demoUserForm : demoDepartmentForm.getDemoUserForms()) {
			demoUserForm.setDepartmentId(demoDepartmentForm.getDepartmentId());
			if(Strings.isEmpty(demoUserForm.getUserId())){
				demoUserForm.setUserId(ObjectHelper.getUUID());
			}

			DemoUserModel demoUserModel = new DemoUserModel();
			demoUserForm.copyTo(demoUserModel);
			
    		String actionType = demoUserForm.getActionType();
			switch (actionType) {
				case ActionModel.ACTION_TYPE_INSERT:
					demoUserModel.setCreateTime(new Date());
					demoUserModel.setCreateUserId(VariableFactory.getUserId());		
					break;
				case ActionModel.ACTION_TYPE_UPDATE:
					demoUserModel.setUpdateTime(new Date());
					demoUserModel.setUpdateUserId(VariableFactory.getUserId());		
					break;
			}
			demoUserModels.add(demoUserModel);
		}
		return demoUserModels;
	}
}